package com.example.springsecuritydemo.config;

import com.alibaba.fastjson2.JSON;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
/**
 * 自定义权限不足处理器
 */
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        String localizedMessage = accessDeniedException.getLocalizedMessage();

        HashMap result = new HashMap();
        result.put("code",403);
        result.put("msg","没有权限"+localizedMessage); //只将异常信息返回给前端

        String json= JSON.toJSONString(result);

        //相应JSON结果，返回json数据给前端
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);
    }
}
